package web;

import com.fasterxml.jackson.databind.ObjectMapper;
import service.UserService;
import service.impl.UserServiceImpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/checkLogin")
public class CheckLoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        Map<String,String> loginCookies = new HashMap<>(8);
        Map<String,Object> msg = new HashMap<>(8);
        ObjectMapper om = new ObjectMapper();
        Cookie[] cookies = request.getCookies();
        for(Cookie cookie:cookies){
            String name = cookie.getName();
            if("PWM".equals(name) || "UNM".equals(name) ||"uid".equals(name)){
                loginCookies.put(name,cookie.getValue());
            }
        }
        if(loginCookies.size()<3){
            //登录所需cookies缺少
            msg.put("msg","已登录");
            msg.put("isLogin",false);
            om.writeValue(response.getOutputStream(),msg);
        }else {
            UserService us = new UserServiceImpl();
            Boolean isLogin = us.checkUserloginCookies(loginCookies.get("PWM"), loginCookies.get("UNM"), Integer.parseInt(loginCookies.get("uid")));
            msg.put("msg","已登录但也没有完全登录");
            msg.put("isLogin",isLogin);
            om.writeValue(response.getOutputStream(),msg);
        }
    }
}
